﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using NETCore.Auth.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using Auth.Classic.Filters;
namespace NETCore.Auth.Controllers
{
    [MyActionAuthrizaFilter]
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            if (!HttpContext.Request.Cookies.TryGetValue("LoginType", out string loginType))
            {
                TempData["err"] = "用户未登录";
                return RedirectToAction("Login", "Account");
            }
            if (loginType == null)
            {
                return RedirectToAction("Login", "Account");
            }
            string userString = string.Empty;
            if (loginType == "cookie")
            {
                //CurrentUser user = new CurrentUser();
                HttpContext.Request.Cookies.TryGetValue("CurrentUser", out userString);
            }
            else
            {
                userString = HttpContext.Session.GetString("CurrentUser");
            }

            if (userString == null)
            {
                return RedirectToAction("Login", "Account");
            }

            ViewData["LoginType"] = loginType;
            CurrentUser currentUser = JsonSerializer.Deserialize<CurrentUser>(userString);

            return View(currentUser);

        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
